import Vue from 'vue'
import VueRouter from 'vue-router'
import Import from "less/lib/less/tree/import";

const Login = () => import('views/login/Login')
const Home = () => import('views/home/Home')
const Users = () => import('views/users/Users')
const Roles = () => import('views/roles/Roles')
const Welcome = () => import('views/welcome/Welcome')
// 1.安装插件
Vue.use(VueRouter)

// 2.创建router
const routes = [
  {
    path: '',
    redirect: '/login'
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      {path: '/welcome', component: Welcome},
      {path: '/users', component: Users},
      {path: '/roles', component: Roles}
    ]
  },
  {
    path: '/users',
    component: Users
  },
  {
    path: '/login',
    component: Login
  }
]

const router = new VueRouter({
  routes,
  mode: 'history'
})

//添加路由守卫，控制访问权限
router.beforeEach((to, from, next) => {
  //访问login，直接放行
  if (to.path === '/login') return next()
  //若不是，检查token是否存在，有放行，没有跳转到login
  const tokenStr = sessionStorage.getItem('token')

  if (!tokenStr) return next('/login')
  next()
})

export default router
